package org.rc.web;

import org.rc.dao.GenericDao;
import org.rc.model.SearchTerm;
import org.rc.six.Document;
import org.rc.six.SearchService;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Search servlet. Handle requests for /autoCompleteSearch.
 * 
 */
public class SearchServlet extends IndexServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchServlet.class);
    protected SearchService searchService = new SearchService();
    private GenericDao<SearchTerm> searchTermDao = new GenericDao<SearchTerm>(SearchTerm.class);

    /**
     * Process GET. Handle auto complete autoCompleteSearch.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String term = request.getParameter("term");
        if(term!=null) {
            response.setContentType("application/json");
            response.getWriter().write(searchService.autoCompleteSearch(term).toString());
        } else {
            forward(request,response,"search.jsp");
        }
    }

    /**
     * Handle the post from the autoCompleteSearch form
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String search = request.getParameter("search");
        LOGGER.debug("searching for:"+search);
        Collection<String> matches = searchService.termSearch(search);
        if(matches!=null && matches.size()==1) {
            LOGGER.debug("found exact match for "+ search+ " going to persist this search");
            Document doc = fromJson((String) matches.toArray()[0]);
            String key = doc.getId();
            LOGGER.debug("key is " + key);
            String qs = buildLinkQueryString(key);
            if(key.startsWith("Race")) {
                searchTermDao.put(new SearchTerm(search,"race?id=" + qs));
                response.sendRedirect("race?id=" + qs);
            } else if(key.startsWith("Athlete")) {
                searchTermDao.put(new SearchTerm(search,"athlete?id=" + qs));
                response.sendRedirect("athlete?id=" + qs);
            }
        } else {
            request.setAttribute("hits", matches);
            forward(request,response,"search.jsp");
        }
    }

    private String buildLinkQueryString(String key) {
        return key.substring(key.indexOf("(")+1, key.indexOf(")"));
    }

    private Document fromJson(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, Document.class);
    }
}
